/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import ejb.common.FotoManagerLocal;
import entity.Foto;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import utility.ExceptionThrower;
import utility.ResourceBundleLoader;

/**
 *
 * @author Carmela
 */
public class AggiungiFoto {
    @EJB
    private FotoManagerLocal fotoManager;

    private List<Foto> fotolist;
    
    public void handleFoto(FileUploadEvent event){
        FacesContext fc=FacesContext.getCurrentInstance();
        ResourceBundle rb=ResourceBundleLoader.getResourceBundle(fc);
        InputStream is = null;
        try {
            UploadedFile uf=event.getFile();
            is = uf.getInputstream();
            String nomeFile=uf.getFileName();
            byte[] fotoByte=IOUtils.toByteArray(is);
            Foto f=new Foto();
            f.setNome(nomeFile);
            f.setFoto(fotoByte);
            if(fotoManager.esisteFoto(f)){
               ExceptionThrower.throwMessageError(fc, rb, "aggiuntaFotoErrorM");
               return;
            }
            fotoManager.creaFoto(f);
            System.out.println("foto caricata");
            ExceptionThrower.throwMessageInfo(fc, rb, "aggiuntaFotoInfoM", nomeFile);
            init();
        } catch (IOException ex) {
            Logger.getLogger(RegistrazioneProdotto.class.getName()).log(Level.SEVERE, null, ex);
            ExceptionThrower.throwMessageError(fc, rb, "aggiuntaFotoErrorM");
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(RegistrazioneProdotto.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Get the value of fotolist
     *
     * @return the value of fotolist
     */
    public List<Foto> getFotolist() {
        return fotolist;
    }

    /**
     * Set the value of fotolist
     *
     * @param fotolist new value of fotolist
     */
    public void setFotolist(List<Foto> fotolist) {
        this.fotolist = fotolist;
    }

    /**
     * Creates a new instance of AggiungiFoto
     */
    public AggiungiFoto() {
    }
    
    @PostConstruct
    public void init(){
        this.fotolist=fotoManager.getFotoProdotti();
    }
}
